package openbang.account.service.util;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import openbang.account.service.vo.CacheKeyDefine;
import openbang.account.service.vo.UserLoginInfo;

/**
 * 处理Session的对象。
 * 
 * 放置 UserLoginInfo
 * 
 * 注：考虑到 分布式 , 改用 Cache存储 -- 2010-03-31 发现 几分钟后 SESSION_ALL 值被清除了, 搞不懂。
 * 
 * 
 * @author aibo zeng
 *
 */

public class SessionHelper {
	
	private static final Logger log = Logger.getLogger(SessionHelper.class.getName());    
	public static UserLoginInfo getUserLoginInfo(HttpServletRequest request){
    	UserLoginInfo user = null;
    	HttpSession session = request.getSession(true);
    	//Object obj = session.getAttribute(CacheKeyDefine.SESSION_USERINFO);
    	Object obj = CacheHelper.get(CacheKeyDefine.SESSION_PREFIX + session.getId());
    	if(obj==null){
    		user = new UserLoginInfo();
    		user.setEmail(session.getId());
    		//session.setAttribute(CacheKeyDefine.SESSION_USERINFO, user);
    	}
    	else{
    		user = (UserLoginInfo)obj;
    	}
    	session = null;
    	return user;
    }
    public static void setUserLoginInfo(HttpServletRequest request,UserLoginInfo user){
    	HttpSession session = request.getSession(true);
    	//session.setAttribute(CacheKeyDefine.SESSION_USERINFO, user);
    	CacheHelper.put(CacheKeyDefine.SESSION_PREFIX + session.getId(),user);
    	//CacheHelper.put(CacheKeyDefine.SESSION_ALL ,CacheHelper.getSessionAll().add(session.getId()));
    	session = null;
    }

    public static void updUserLoginInfo(HttpServletRequest request,UserLoginInfo user){
    	HttpSession session = request.getSession(true);
    	//session.setAttribute(CacheKeyDefine.SESSION_PREFIX, user);
    	CacheHelper.update(CacheKeyDefine.SESSION_PREFIX + session.getId(),user);
    	session = null;
    }

    public static void updUserLoginInfo(HttpServletRequest request){
    	HttpSession session = request.getSession(true);
    	UserLoginInfo user = getUserLoginInfo(request);
    	user.setLastAccessDate(new Date());
    	CacheHelper.update(CacheKeyDefine.SESSION_PREFIX + session.getId(),user);
    	//session.setAttribute(CacheKeyDefine.SESSION_USERINFO, user);
    	session = null;
    }
    
    /**
     * 获取应用程序所在的服务和端口
     * @param request
     * @return
     */
    public static String getAppUrl(HttpServletRequest request) {
	    String servletUrl = request.getRequestURL().toString(); //如：http://localhost:8888/accountService
	    String resourcePath = request.getRequestURI();          //如：/accountService
	    //log.warning(servletUrl);
	    //log.warning(resourcePath);
	    //log.warning(request.getContextPath());
	    return servletUrl.replace(resourcePath, "");  //结果为：http://localhost:8888
	}
    public static String getLoginUrl(HttpServletRequest request) {
        UserService userService = UserServiceFactory.getUserService();
        return userService.createLoginURL(getAppUrl(request));
    }
    public static String getLogoutUrl(HttpServletRequest request) {
        UserService userService = UserServiceFactory.getUserService();
        return userService.createLogoutURL(getAppUrl(request));
    }
    
    private SessionHelper(){    	
    }
    
    public static void main(String[] args){
    	UUID uuid = UUID.randomUUID();
    	System.out.println(uuid.toString());
    }
    
    public static void forwardToErrorPage(String theAction,String theReason,String theSolution, HttpServletRequest req, HttpServletResponse resp){
    	req.setAttribute("theAction", theAction);
    	req.setAttribute("theUrl", req.getRequestURL().toString());
    	req.setAttribute("theReason", theReason);
    	req.setAttribute("theSolution", theSolution);
    	try {
			req.getRequestDispatcher("/sorry.jsp").forward(req, resp);
		} catch (ServletException e) {
		} catch (IOException e) {
		}
    }

    public static void redirectToErrorPage(String theAction,String theReason,String theSolution, HttpServletRequest req, HttpServletResponse resp){
    	String redirectUrl = "/sorry.jsp?theAction="+theAction+"&theUrl="+req.getRequestURL().toString()+"&theReason="+theReason+"&theSolution="+theSolution;
    	try {
    		resp.sendRedirect(redirectUrl);
		} catch (IOException e) {
		}
    }
    
    public static void forwardToSuccessPage(String theAction,String theRemark, HttpServletRequest req, HttpServletResponse resp){
    	req.setAttribute("theAction", theAction);
    	req.setAttribute("theRemark", theRemark);
    	try {
			req.getRequestDispatcher("/success.jsp").forward(req, resp);
		} catch (ServletException e) {
		} catch (IOException e) {
		}
    }
}
